package ssm.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import ssm.pojo.User;
import ssm.service.UserSerivce;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@Controller
public class UserController {
    @Autowired
    private UserSerivce userSerivce;

    /**
     * 实现账户的登录
     * @param username 用户名
     * @param password 密码
     * @param session
     * @return 登陆界面
     */
    @RequestMapping("/login_success")
    public String login(String username, String password, HttpSession session){
        User user = userSerivce.getUser(username, password);
        if (user==null){
            return "pages/user/login";
        }
        session.setAttribute("user",user);
        return "pages/user/login_success";
    }
    @RequestMapping("/login")
    public String returnLogin(HttpSession session){
        session=null;
        return "redirect:/";
    }

    /**
     * 验证注册成功
     * @param session
     * @param user
     * @param kaptcha
     * @return
     */
    @RequestMapping("/regist_success")
    public String registSuccess(HttpSession session,User user,String kaptcha){
        String testKaptcha = (String)session.getAttribute("KAPTCHA_SESSION_KEY");
        if (testKaptcha.equals(kaptcha)){
            userSerivce.saveUser(user);
            return "pages/user/regist_success";
        }
        return "redirect:/regist_success";
    }

    /**
     * 检测注册时用户名是否存在
     * @param uname
     * @return
     */
    @RequestMapping("/register/{uname}")
    @ResponseBody
    public String ckUname(@PathVariable("uname") String uname){
        User user = userSerivce.getUserByName(uname);
        if (user!=null){
            //用户已被占用
            return "1";
        }
        return "0";
    }
}
